package com.cy.myblog.service.impl;

import com.cy.myblog.dao.UserDaoI;
import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.User;
import com.cy.myblog.service.UserServiceI;
import com.cy.myblog.util.Encrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl implements UserServiceI{

	private UserDaoI userDao;
	
	public UserDaoI getUserDao() {
		return userDao;
	}

	@Resource(name="userDynamicDao")
	public void setUserDao(UserDaoI userDao) {
		this.userDao = userDao;
	}

	public void save(User user) {
		user.setId(UUID.randomUUID().toString());
		user.setCreatime(new Date());
		user.setPassword(Encrypt.md5(user.getPassword()));
		Tuser tuser = new Tuser();
		BeanUtils.copyProperties(user, tuser);
		userDao.save(tuser);
	}

	public Tuser getById(String id){
		return userDao.getById(Tuser.class, id);
	}

	@Override
	public Tuser getByHql(User user) {
		String hql = "from Tuser where account = :account and password = :password";
		if(user != null){
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("account", user.getAccount());
			params.put("password", user.getPassword());
			return userDao.getByHql(hql, params);
		}
		return null;
	}

	public Tuser getByHql(String account){
		String hql = "from Tuser where account = :account";
		if("".equals(account) || account == null){
			return null;
		}

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("account", account);
		return userDao.getByHql(hql, params);
	}

	@Override
	public Tuser update(User user) {
		Tuser tu = getById(user.getId());
		BeanUtils.copyProperties(user,tu,new String[]{"id","account","password","creatime","logintime","ipaddress","state"});
		userDao.update(tu);
		return tu;
	}

	@Override
	public void update(Tuser user) {
		userDao.update(user);
	}

}
